/**
 *  Copyright 2002-2009 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package foo.bar.forum.security;

import org.jsecurity.realm.Realm;
import org.jsecurity.session.Session;
import org.jsecurity.subject.PrincipalCollection;
import org.jsecurity.subject.Subject;
import org.jsecurity.web.DefaultWebSecurityManager;

import java.net.InetAddress;
import java.util.Collection;

/**
 * An extended {@link org.jsecurity.mgt.SecurityManager} that allows {@link Subject} that it
 * creates to have one principle ({@link UserAccountRealm#ANONYMOUS_USER_ACCOUNT} when it's an
 * anonymous user. 
 *
 * @author tmjee
 * @version $Date: 2009-03-14 14:53:07 +0800 (Sat, 14 Mar 2009) $ $Id$
 */
public class AnonymousSubjectAwareDefaultWebSecurityManager extends DefaultWebSecurityManager {

    public AnonymousSubjectAwareDefaultWebSecurityManager() {
        super();
    }

    public AnonymousSubjectAwareDefaultWebSecurityManager(Realm singleRealm) {
        super(singleRealm);
    }

    public AnonymousSubjectAwareDefaultWebSecurityManager(Collection<Realm> realms) {
        super(realms);
    }


    protected Subject createSubject(PrincipalCollection principals, Session existing,
                                    boolean authenticated, InetAddress inetAddress) {
        if(principals == null || principals.isEmpty()) {
            if (null == UserAccountRealm.ANONYMOUS_USER_ACCOUNT) {
                throw new RuntimeException("UserAccountRealm.ANONYMOUS_USER_ACCOUNT is null, this should be setup in SetupService, check if SetupService has been configured and started up properly");
            }
            return new AnonymousSubjectAwareDelegatingSubject(
                            UserAccountRealm.ANONYMOUS_USER_ACCOUNT.getPrincipals(),
                            authenticated, inetAddress, existing, this);
        }
        return new AnonymousSubjectAwareDelegatingSubject(principals, authenticated, inetAddress, existing, this);
    }


}
